/**
 * Created by admin on 2018/12/17.
 */

 // 时间格式化
const timeformat = function (str, format, tissue) {
    var myDate = new Date();
    str = (str == 0 || !str || str == 'undefined' || str == NaN) ? myDate.getTime() : str;
    str = (typeof str == 'string') ? str.replace(/\-/g, '/') : str;
    (!format || format == '') ? format = 'y-m-d h:i:s': format;
    var nowstamp = parseInt(myDate.getTime() / 1000),
        itemtime = parseInt(str),
        year, m, d, h, i, s;
    if (format == 'timestamp') {
        (str === +str) ? str = parseInt(str): str = Date.parse(str);
        if (str > 100000000000) {
            str = str / 1000;
        }
        return str;
    }
    if (itemtime < 10000) {
        //普通时间直接转换
        itemtime = Date.parse(str);
    }
    if (itemtime > 100000000000) {
        itemtime = itemtime / 1000;
    }
    var timebe = nowstamp - itemtime;
    if (tissue && tissue > -1 && tissue < 864000 && timebe < tissue) {
        if (timebe > 86400) {
            //超过1天，按天计算
            return Math.floor(timebe / 86400) + '天前';
        } else if (timebe > 3600) {
            //超过1小时，按小时计算
            return Math.floor(timebe / 3600) + '小时前';
        } else if (timebe > 59) {
            //按分钟计算
            return Math.ceil(timebe / 60) + '分钟前';
        } else {
            return '刚刚';
        }
    } else {
        itemtime = myDate.setTime(itemtime * 1000);
        year = myDate.getFullYear();
        m = (myDate.getMonth() + 1 < 10) ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1;
        d = (myDate.getDate() < 10) ? '0' + (myDate.getDate()) : myDate.getDate();
        h = (myDate.getHours() < 10) ? '0' + (myDate.getHours()) : myDate.getHours();
        i = (myDate.getMinutes() < 10) ? '0' + (myDate.getMinutes()) : myDate.getMinutes();
        s = (myDate.getSeconds() < 10) ? '0' + (myDate.getSeconds()) : myDate.getSeconds();

        if ("object" == format.toLowerCase()) {
            return {
                year: year,
                mon: m,
                day: d,
                hour: h,
                min: i,
                sec: s
            };
        }

        return format.replace('y', year).replace('m', m).replace('d', d).replace('h', h).replace('i', i).replace('s', s);
    }
}


function prevHeight(type = 1) {
    if (type === 1) {
        document.querySelector('body').style.height = '100%'
        document.querySelector('html').style.height = '100%'
        document.querySelector('#app').style.height = '100%'
    } else {
        document.querySelector('body').style.height = ''
        document.querySelector('html').style.height = ''
        document.querySelector('#app').style.height = ''
    }
}

function deepAssign(to, from) {
    for (let key in from) {
        if (!to[key] || typeof to[key] !== 'object') {
            to[key] = from[key]
        } else {
            deepAssign(to[key], from[key])
        }
    }
}

function createAddAPI(baseObj) {
    return function add(...args) {
        if (typeof args[0] === 'string') {
            args[0] = {
                [args[0]]: args[1]
            }
        }
        deepAssign(baseObj, args[0])
    }
}

function judgeTypeFnCreator(type) {
    const toString = Object.prototype.toString
    return function isType(o) {
        return toString.call(o) === `[object ${type}]`
    }
}
const camelizeRE = /-(\w)/g
function camelize(str) {
    str = String(str)
    return str.replace(camelizeRE, function (m, c) {
        return c ? c.toUpperCase() : ''
    })
}

function kebab(str) {
    str = String(str)
    return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}
const typesReset = {
    _set(obj, key, value) {
        obj[key] = value
    },
    string(obj, key) {
        typesReset._set(obj, key, '')
    },
    number(obj, key) {
        typesReset._set(obj, key, 0)
    },
    boolean(obj, key) {
        typesReset._set(obj, key, false)
    },
    object(obj, key, value) {
        if (Array.isArray(value)) {
            typesReset._set(obj, key, [])
        } else {
            typesReset._set(obj, key, {})
        }
    }
}
function resetTypeValue(obj, key, defVal) {
    if (defVal !== undefined) {
        return typesReset._set(obj, key, defVal)
    }
    if (key) {
        const value = obj[key]
        const resetHandler = typesReset[typeof value]
        resetHandler && resetHandler(obj, key, value)
    } else {
        Object.keys(obj).forEach((key) => {
            resetTypeValue(obj, key)
        })
    }
}

function parallel(tasks, cb) {
    let doneCount = 0
    let results = []
    const tasksLen = tasks.length
    if (!tasksLen) {
        return cb(results)
    }
    tasks.forEach((task, i) => {
        task((ret) => {
            doneCount += 1
            results[i] = ret
            if (doneCount === tasksLen) {
                // all tasks done
                cb(results)
            }
        })
    })
}

function cb2PromiseWithResolve(cb) {
    let promise
    if (typeof window.Promise !== 'undefined') {
        const _cb = cb
        promise = new window.Promise((resolve) => {
            cb = (data) => {
                _cb && _cb(data)
                resolve(data)
            }
        })
        promise.resolve = cb
    }
    return promise
}

function debounce(func, wait, immediate, initValue) {
    let timeout
    let result = initValue

    const later = function (context, args) {
        timeout = null
        if (args) {
            result = func.apply(context, args)
        }
    }

    const debounced = function (...args) {
        if (timeout) {
            clearTimeout(timeout)
        }
        if (immediate) {
            const callNow = !timeout
            timeout = setTimeout(later, wait)
            if (callNow) {
                result = func.apply(this, args)
            }
        } else {
            timeout = setTimeout(() => {
                later(this, args)
            }, wait)
        }

        return result
    }

    debounced.cancel = function () {
        clearTimeout(timeout)
        timeout = null
    }

    return debounced
}

function processComponentName(Component, { prefix = '', firstUpperCase = false } = {}) {
    const name = Component.name
    const pureName = name.replace(/^cube-/i, '')
    let camelizeName = `${camelize(`${prefix}${pureName}`)}`
    /* istanbul ignore if */
    if (firstUpperCase) {
        camelizeName = camelizeName.charAt(0).toUpperCase() + camelizeName.slice(1)
    }
    return camelizeName
}

function parsePath(obj, path = '') {
    const segments = path.split('.')
    let result = obj
    for (let i = 0; i < segments.length; i++) {
        const key = segments[i]
        /* istanbul ignore if */
        if (isUndef(result[key])) {
            result = ''
            break
        } else {
            result = result[key]
        }
    }
    return result
}

const isFunc = judgeTypeFnCreator('Function')
const isUndef = judgeTypeFnCreator('Undefined')
const isArray = judgeTypeFnCreator('Array')
const isString = judgeTypeFnCreator('String')
const isObject = judgeTypeFnCreator('Object')
const isNumber = judgeTypeFnCreator('Number')
const findIndex = function (ary, fn) {
    if (ary.findIndex) {
        return ary.findIndex(fn)
    }
    /* istanbul ignore next */
    let index = -1
    /* istanbul ignore next */
    ary.some(function (item, i, ary) {
        const ret = fn.call(this, item, i, ary)
        if (ret) {
            index = i
            return ret
        }
    })
    /* istanbul ignore next */
    return index
}

const mathChoose = function (arr, size) {
    var allResult = [];
    let func = function (arr, size, result) {
        var arrLen = arr.length;
        if (size > arrLen) {
            return;
        }
        if (size == arrLen) {
            allResult.push([].concat(result, arr))
        } else {
            for (var i = 0; i < arrLen; i++) {
                var newResult = [].concat(result);
                newResult.push(arr[i]);

                if (size == 1) {
                    allResult.push(newResult);
                } else {
                    var newArr = [].concat(arr);
                    newArr.splice(0, i + 1);
                    func(newArr, size - 1, newResult);
                }
            }
        }
    };
    func(arr, size, []);
    return allResult;
};

/*彩票方法 根据玩法名称写的方法*/
const lhc_lxlw = function (tag_content, arr) {
    let odds;
    let i = arr.indexOf('狗');
    if (i >= 0) {
        return tag_content['狗'];
    } else {
        return tag_content[arr[0]];
    }
}

const lhc_lm_odds = function (tag_content, play) {
    let odds = '';
    switch (play) {
        case 'lhc_sanzhonger':
            odds = tag_content['sz2'];
            break;
        case 'lhc_sanquanzhong':
            odds = tag_content['sqz'];
            break;
        case 'lhc_erquanzhong':
            odds = tag_content['eqz'];
            break;
        case 'lhc_erzhongte':
            odds = tag_content['ezt'];
            break;
        case 'lhc_techuan':
            odds = tag_content['tc'];
            break;
        case 'lhc_siquanzhong':
            odds = tag_content['siqz'];
            break;
    }

    return odds;
}

const wxPay = ({data, success = ()=>{}, fail = ()=>{}} = {}) => {
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": data.appId,     //公众号名称，由商户传入     
            "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数     
            "nonceStr": data.nonceStr, //随机串     
            "package": data.package,     
            "signType": data.signType || "MD5",         //微信签名方式：     
            "paySign": data.paySign //微信签名 
        },
        function(res){
            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                return success(res)
            }
            return fail(res)
        }
    )
}

const isWechat = () => {
    let ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == 'micromessenger';
}


export {
    findIndex,
    deepAssign,
    createAddAPI,
    resetTypeValue,
    parallel,
    cb2PromiseWithResolve,
    debounce,
    processComponentName,
    parsePath,
    camelize,
    kebab,
    prevHeight,
    isUndef,
    isFunc,
    isArray,
    isString,
    isObject,
    isNumber,
    mathChoose,
    lhc_lxlw,
    lhc_lm_odds,
    timeformat,
    wxPay,
    isWechat
};
export default {
    findIndex,
    deepAssign,
    createAddAPI,
    resetTypeValue,
    parallel,
    cb2PromiseWithResolve,
    debounce,
    processComponentName,
    parsePath,
    camelize,
    kebab,
    prevHeight,
    isUndef,
    isFunc,
    isArray,
    isString,
    isObject,
    isNumber,
    mathChoose,
    lhc_lxlw,
    lhc_lm_odds,
    timeformat,
    wxPay,
    isWechat
}


